//左侧大类导航
import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provide/provide.dart';
import 'package:study_flutter/yzhg/dartTools/YEventBusUtil.dart';
import 'package:study_flutter/yzhg/project/service/service_method.dart';
import 'package:study_flutter/yzhg/project/shop/content/Content.dart';
import 'package:study_flutter/yzhg/project/shop/event/YEventBusBean.dart';
import 'package:study_flutter/yzhg/project/shop/model/CateGoodsBean.dart';
import 'package:study_flutter/yzhg/project/shop/model/YCatagoryBean.dart';
import 'package:study_flutter/yzhg/project/shop/provide/CategoryGoodsList.dart';
import 'package:study_flutter/yzhg/project/shop/provide/ChildCategory.dart';

import 'CategoryEventBean.dart';

class LeftCatGeGory extends StatefulWidget {
  @override
  _LeftCatGeGoryState createState() => _LeftCatGeGoryState();
}

class _LeftCatGeGoryState extends State<LeftCatGeGory> {
  List<YCatagoryItem> lists = [];

  //获取商品列表
  List<CateGoodsListBean> cateGoodsLists = [];

  //设置索引 默认第0个
  var currentIndex = 0;

  StreamSubscription<CategoryEventBean> _event;

  @override
  void initState() {
    _getCategoryData();
    super.initState();

    /*监听EventBus*/
    _event = YEventBusUtil.getInstance().on<CategoryEventBean>().listen((data) {
      //获取到 二级列表数据
      //请求网络数据
      _getGoodsListData(
          data.mallCategoryId, data.mallSubId, data.isRefresh, data.page);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: ScreenUtil().setWidth(180),
      decoration: BoxDecoration(
          border: Border(right: BorderSide(width: 1, color: Colors.black12))),
      child: ListView.builder(
        itemCount: lists.length,
        itemBuilder: (context, index) {
          return _leftInkWell(index);
        },
      ),
    );
  }

  Widget _leftInkWell(int index) {
    return InkWell(
      //点击左侧 修改右侧数据
      onTap: () {
        setState(() {
          //设置当前索引
          currentIndex = index;
        });
        //获取当前条目
        YCatagoryItem categoryItem = lists[index];
        //获取到子类数据
        List<BxMallSubDto> childList = categoryItem.bxMallSubDto;
        //将子类数据抛到右侧   页面
        //  Provide.value<ChildCategory>(context).getChildCategory(childList);
        _setProvide(childList);
        //请求第一条数据
        _getGoodsListData(categoryItem.mallCategoryId, "", true, 1);
        //Eventbus通知  修改了二级角标
        YEventBusUtil.getInstance()
            .fire(YEventBusBean(Content.EVENT_CATEGORY_TITLE, eventIng: 0));
      },
      child: Container(
        height: ScreenUtil().setHeight(100),
        // padding: EdgeInsets.only(left: 10, top: 20, bottom: 20),
        alignment: Alignment.center,
        decoration: BoxDecoration(
            color: (currentIndex == index) ? Colors.black12 : Colors.white,
            border:
                Border(bottom: BorderSide(width: 1, color: Colors.black12))),
        child: Text(
          lists[index].mallCategoryName,
          style: TextStyle(
              fontSize: ScreenUtil().setSp(28),
              color: (currentIndex == index) ? Colors.pink : Colors.black),
        ),
      ),
    );
  }

  _getCategoryData() async {
    await getCategory().then((val) {
      var data = json.decode(val.toString());
      YCatagoryBean category = YCatagoryBean.fromJson(data);

      setState(() {
        lists = category.data;
        //设置当前索引为0
        currentIndex = 0;
      });
      //设置第一个数据标识
      var firstList = lists[0].bxMallSubDto;
      _setProvide(firstList);
      //请求第一条数据
      if (lists.length > 0)
        _getGoodsListData(lists[0].mallCategoryId, "", true, 1);
    });
  }

  /*获取商品详情*/
  _getGoodsListData(categoryId, categorySubId, bool isRefresh, page) async {
    var formData = {
      "categoryId": categoryId,
      "categorySubId": categorySubId,
      "page": "$page"
    };
    await getCategoryGoodsData(formData).then((val) {
      var data = json.decode(val.toString());
      CateGoodsBean cateGoodsBean = CateGoodsBean.fromJson(data);
      //获取到集合数据
      List<CateGoodsListBean> cateGoodsList = cateGoodsBean.data;

      int eventPosition = 0;
      //如果是刷新页面 清除数据
      if (isRefresh) {
        this.cateGoodsLists.clear();
        if (cateGoodsList == null || cateGoodsList.length == 0) {
          Fluttertoast.showToast(msg: "获取数据为空，处理空布局");
          eventPosition = Content.EVENT_GOODS_REFRESH_EMPTY;
        } else {
          //将获取到的数据添加到 集合中
          eventPosition = Content.EVENT_REFRESH_GOODS_REFRESH;
        }
      } else {
        if (cateGoodsList == null || cateGoodsList.length == 0) {
          //没有更多数据  EVENT_GOODS_REFRESH_MORE_EMPTY
          eventPosition = Content.EVENT_GOODS_REFRESH_MORE_EMPTY;
        } else {
          //将获取到的数据添加到 集合中
          eventPosition = Content.EVENT_REFRESH_GOODS_REFRESH;
        }
      }
      //判空
      if (cateGoodsList != null) this.cateGoodsLists.addAll(cateGoodsList);
      _setGoodsListProvide(cateGoodsLists, categoryId, categorySubId,page);
      //页面刷新成功  EventBus通知页面
      YEventBusUtil.getInstance()
          .fire(YEventBusBean(eventPosition, eventBool: isRefresh));
    });
  }

  /*设置Provide*/
  _setProvide(List<BxMallSubDto> childList) {
    Provide.value<ChildCategory>(context).getChildCategory(childList);
  }

  /*设置商品列表数据*/
  _setGoodsListProvide(
      List<CateGoodsListBean> list, String categoryId, String categorySubId,int page) {
    Provide.value<CategoryGoodsListProvide>(context)
        .getGoodsList(list, categoryId, categorySubId,page);
  }

  @override
  void dispose() {
    super.dispose();
    _event.cancel();
  }
}
